#include "guiwindow.h"
#include <gl\glfw.h>
#include "input.h"
#include "guimgr.h"

CGuiWindow::CGuiWindow()
{
	m_bMouseOver = false;
	m_bDragging = false;
}

CGuiWindow::~CGuiWindow()
{
	
}

void CGuiWindow::Initialize(vec2f& pos, vec2f& dim, std::string& caption)
{
	m_v2f_Pos = pos;
	m_v2f_Dim = dim;
	m_sCaption = caption;
}

void CGuiWindow::Initialize(vec2f& pos, vec2f& dim, std::string& caption, GuiColor& color)
{
	m_v2f_Pos = pos;
	m_v2f_Dim = dim;
	m_sCaption = caption;
	m_Color = color;
}

bool CGuiWindow::IsMouseOverTitleBar()
{
	int32_t x, y;
	x = y = 0;
	CInputManager::GetMousePosition(x, y);

	return x >= m_v2f_Pos.x 
	&& x < m_v2f_Pos.x + m_v2f_Dim.x
	&& y >= m_v2f_Pos.y
	&& y < m_v2f_Pos.y + 20;
}

bool CGuiWindow::WasMouseInsideTitleBar()
{
	int32_t x, y;
	x = y = 0;
	CInputManager::GetMouseDownPos(x, y);

	return x >= m_v2f_Pos.x 
	&& x < m_v2f_Pos.x + m_v2f_Dim.x
	&& y >= m_v2f_Pos.y
	&& y < m_v2f_Pos.y + 20;
}

bool CGuiWindow::IsDraggable()
{
	return IsMouseOverTitleBar() && WasMouseInsideTitleBar();
}

void CGuiWindow::Update()
{
	int32_t clientwidth, clientheight;
	clientwidth = clientheight = 0;
	CGuiManager::GetClientArea(clientwidth, clientheight);

	if(m_v2f_Pos.x > clientwidth-4)
		m_v2f_Pos.x = static_cast<float>(clientwidth-4);

	if(m_v2f_Pos.x < -m_v2f_Dim.x+4)
		m_v2f_Pos.x = static_cast<float>(-m_v2f_Dim.x+4);

	if(m_v2f_Pos.y < -m_v2f_Dim.y+4)
		m_v2f_Pos.y = static_cast<float>(-m_v2f_Dim.y+4);

	if(m_v2f_Pos.y > clientheight-4)
		m_v2f_Pos.y = static_cast<float>(clientheight-4);

	if(m_bDragging)
	{
		int32_t x, y;
		x = y = 0;
		CInputManager::GetMousePosition(x, y);

		int32_t lx, ly;
		lx = ly = 0;
		CInputManager::GetLastMousePosition(lx, ly);
		
		int32_t dx, dy;
		dx = dy = 0;
		dx = x - lx;
		dy = y - ly;

		m_v2f_Pos.x += dx;
		m_v2f_Pos.y += dy;
	}
}

void CGuiWindow::Render()
{
	glColor4ub(m_Color.R, m_Color.G, m_Color.B, m_Color.A);
	CGuiManager::RenderViewport(m_v2f_Pos, m_v2f_Dim);

	vec2f bdim = m_v2f_Dim;
	bdim.y = 20;

	glColor4ub(28, 185, 215, 255);
	CGuiManager::RenderViewport(m_v2f_Pos, bdim);
	glColor4ub(186, 236, 248, 255);
	glPushMatrix();
	glScalef((bdim.x-2)/(bdim.x), (bdim.y-2)/(bdim.y), 1.0f);
	CGuiManager::RenderViewport(m_v2f_Pos, bdim);
	glPopMatrix();
}


void CGuiWindow::Dispose()
{
	
}
